package com.my.cloud.controller;

import com.my.cloud.entities.PayDTO;
import com.my.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/7 19:33
 */
@RestController
@RequestMapping("/consumer/pay")
public class OrderController {
    
    // 硬编码
    //public static final String PaymentSrv_URL = "http://localhost:8001";
    
    // 服务注册中心上的微服务名称
    public static final String PaymentSrv_URL = "http://cloud-payment-service";
    @Resource
    private RestTemplate restTemplate;
    
    @GetMapping(value = "add")
    public ResultData addOrder(PayDTO payDTO){
        ResultData resultData = restTemplate.postForObject(PaymentSrv_URL + "/pay/add", payDTO, ResultData.class);
        return resultData;
    }
    
    @GetMapping("/get/{id}")
    public ResultData getPayInfo(@PathVariable("id") Integer id){
        
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/" + id, ResultData.class, id);
                
    }
    
    @GetMapping("/del/{id}")
    public void delOrder(@PathVariable("id") Integer id){
        restTemplate.delete(PaymentSrv_URL + "/pay/del/" + id,id);
    }
    
    @GetMapping("/update")
    public void updateOrder(PayDTO payDTO){
        System.out.println("payDTO = " + payDTO);
        restTemplate.put(PaymentSrv_URL + "/pay/update",payDTO);
    }
    
    @GetMapping("/get/info")
    private String getInfoByConsul(){
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/info", String.class);
    }
    
    
    @Resource
    private DiscoveryClient discoveryClient;
    
    @GetMapping("discovery")
    public String discovery(){

        List<String> services = discoveryClient.getServices();
        services.forEach(System.out::println);

        System.out.println("=============================");

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
        }
        
        return instances.get(0).getServiceId() + ":" + instances.get(0).getPort();

    }
    
    
}
